package cn.gov.pbc.tims.controller;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.gov.pbc.tims.entity.Dept;
import cn.gov.pbc.tims.entity.Task;
import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.service.CommonService;
import cn.gov.pbc.tims.util.ExcelUtil;
import cn.gov.pbc.tims.util.FileOperateUtil;
import cn.gov.pbc.tims.util.HqlGenerateUtil;
import cn.gov.pbc.tims.util.Model;
import cn.gov.pbc.tims.util.Operator;
import cn.gov.pbc.tims.util.PageData;
import cn.gov.pbc.tims.util.Result;

 

/**
 * 查询专用处理类
 * 
 * 
 */
@Controller
@RequestMapping("/")
public class SearchController   {
	private static final Logger LOGGER = LogManager.getLogger(SearchController.class);
	private CommonService commonService;
	private String message;
	@Autowired
	private Operator operator;
	@Autowired 
	private ObjectMapper objectMapper;
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@Autowired
	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}
  @Autowired
  private SessionFactory sessionFactory;

  private Session getCurrentSession() {
     return this.sessionFactory.getCurrentSession();
  }
  /*
   

  @RequestMapping("/ViewYwk") 
  public @ResponseBody PageData searchYwk(Integer page, Integer rows,HttpServletRequest request,HbJrjgywk target) throws Exception{
	 
	  return 	search(page,rows,request,target);
	    }
*/
  @RequestMapping("Task/search") 
  public @ResponseBody PageData searchTask(Integer page, Integer rows,HttpServletRequest request,Task task) throws Exception{
	 User user=operator.getUser();
	 Integer id=user.getDeptId();
	 if(null!=id)
		 {
			 Dept dept=commonService.get(Dept.class, id);
			 if(!dept.getLevel().equals("1"))
				 dept=commonService.get(Dept.class, dept.getUpDeptId());
			 task.setL1DeptId(dept.getId());
		 }
	 String adhql="   order by Id desc";
	 return 	search(page,rows,request,task,adhql);
	 } 
  @RequestMapping("{modelName}/search") 
  public @ResponseBody PageData searchModel(Integer page, Integer rows,HttpServletRequest request,@PathVariable("modelName") String modelName) throws Exception{
	
	  return 	search(page,rows,request,modelName);
	    } 
  
  @RequestMapping("{modelName}/del") 
  public @ResponseBody Result del(int id, @PathVariable("modelName") String modelName) throws Exception{
	 // System.out.println("开始删除：" + Integer.toString(id));
		String packagename="cn.gov.pbc.tims.entity.";
	 	Class clazz=Class.forName(packagename+modelName);
		Object entity = clazz.newInstance();
		// clazz.getMethod("setId").invoke(entity,id);
		// commonService.delete(entity);
		commonService.deleteEntityById(clazz, Integer.valueOf(id));

		Result result = new Result();
		String echoStatement = "删除成功！";
		result.setValue(0, echoStatement);
		return result;
	}
  
  
  
  /* 
  @RequestMapping("/viewXjzx/toExcel/") 
  public ModelAndView viewXjzxToexcel(Integer page, Integer rows,HttpServletRequest request,ViewXjzx target,HttpServletResponse response) throws Exception{
	//String[] titles=request.getParameter("titles").split(",");
	  //String[] fields=request.getParameter("fields").split(",");
	  JsonNode jsonNode=objectMapper.readTree(new File(this.getClass().getResource("/json/model.json").getPath()));	  	  
	  Model m=new Model(jsonNode.get("ViewXjzx"));
		 //表頭
	  String[]  heads=m.getDescriptions();
		 //字段集合
	  String[]  fields=m.getFields();
	  List datas= search(page,rows,request,target,fields);
	  InputStream iss =ExcelUtil.createExcel2(heads,fields, datas);
      String realName = "ViewXjzx.xls";  
      String contentType = "application/octet-stream";  
      FileOperateUtil.download(request, response, contentType,  realName,iss); 
	  return   null;
	    }*/
  @RequestMapping("{modelName}/toExcel") 
  public ModelAndView toExcel(Integer page, Integer rows,HttpServletRequest request,@PathVariable("modelName") String modelName,HttpServletResponse response) throws Exception{
	  //String[] titles=request.getParameter("titles").split(",");
	  //String[] fields=request.getParameter("fields").split(",");
	  JsonNode jsonNode=objectMapper.readTree(new File(this.getClass().getResource("/json/model.json").getPath()));	 
	  JsonNode js=jsonNode.get(modelName);
	  Model m=new Model(js);
		 //表頭
	  String[]  heads=m.getDescriptions();
		 //字段集合
	  String[]  fields=m.getFields();
	  List datas= search(page,rows,request,modelName,fields);
	  InputStream iss =ExcelUtil.createExcel2(heads,fields, datas);
      String realName = modelName+".xls";  
      String contentType = "application/octet-stream";  
      FileOperateUtil.download(request, response, contentType,  realName,iss); 
	  return   null;
	    }
  
  @RequestMapping("{modelName}/toMyExcel") 
  public ModelAndView toMyExcel(Integer page, Integer rows,HttpServletRequest request,@PathVariable("modelName") String modelName,HttpServletResponse response) throws Exception{
	  //String[] titles=request.getParameter("titles").split(",");
	  //String[] fields=request.getParameter("fields").split(",");
	  String[] sss = modelName.split("\\|");
	  String myModelName = (sss.length == 2)?sss[0]:"";
	  String addtionHql = (sss.length == 2)?sss[1]:"";
	  
	  JsonNode jsonNode=objectMapper.readTree(new File(this.getClass().getResource("/json/model.json").getPath()));	 
	  Model m=new Model(jsonNode.get(myModelName));
		 //表頭
	  String[]  heads=m.getDescriptions();
		 //字段集合
	  String[]  fields=m.getFields();
	  
	  //去掉“id”字段
	  int index_h = 0,index_f = 0;
	  List<String> list_heads = new ArrayList<String>();
	  List<String> list_fields = new ArrayList<String>();
	  for  (int i = 0;i<heads.length;i++){
		  if (!heads[i].equals("id")){
			  list_heads.add(index_h, heads[i]);
			  index_h++;
		  }
	  }
	  for  (int i = 0;i<fields.length;i++){
		  if (!fields[i].equals("id")){
			  list_fields.add(index_f, fields[i]);
			  index_f++;
		  }
	  }
	  String[]  heads_new=new String[list_heads.size()];
	  String[]  fields_new=new String[list_fields.size()];
	  for (int j=0;j<list_heads.size();j++){
		  heads_new[j] = list_heads.get(j);
	  }
	  for (int j=0;j<list_fields.size();j++){
		  fields_new[j] = list_fields.get(j);
	  }
	  
	  List datas= search(page,rows,request,myModelName,fields_new,addtionHql);
	  InputStream iss =ExcelUtil.createExcel2(heads_new,fields_new, datas);
      String realName = myModelName+".xls";  
      String contentType = "application/octet-stream";  
      FileOperateUtil.download(request, response, contentType,  realName,iss); 
	  return   null;
	    }
 
  private <T>  PageData search(Integer page, Integer rows,HttpServletRequest request,T searchObj) throws Exception{
	  	String  rigor=request.getParameter("rigor");
		List result=HqlGenerateUtil.installHql(request.getParameterMap(), searchObj, rigor);
	    String hql=(String)result.get(0);
	   // System.out.println(hql);
	    List list=(List)result.get(1);
	    List<T>  results=commonService.createQuery(hql, list, page, rows);
		//count 为总条目数
		Long  count=commonService.getCount(hql, list);
		PageData grid_data=new PageData();
		grid_data.setValue(count.intValue(), results);
		return grid_data;
  }
  private <T>  PageData search(Integer page, Integer rows,HttpServletRequest request,String modelName) throws Exception{
	  	String  rigor=request.getParameter("rigor");
		List result=HqlGenerateUtil.installHql(request.getParameterMap(), modelName, rigor);
	    String hql=(String)result.get(0);
	    List list=(List)result.get(1);
	    List<T>  results=commonService.createQuery(hql, list, page, rows);
		//count 为总条目数
		Long  count=commonService.getCount(hql, list);
		PageData grid_data=new PageData();
		grid_data.setValue(count.intValue(), results);
		return grid_data;
} 
  private <T>  PageData search(Integer page, Integer rows,HttpServletRequest request,T searchObj,String addtionHql) throws Exception{
	  	String  rigor=request.getParameter("rigor");
		List result=HqlGenerateUtil.installHql(request.getParameterMap(), searchObj, rigor);
	    String hql=(String)result.get(0);
	    //System.out.println(hql);
	    hql=hql+addtionHql;
	    List list=(List)result.get(1);
	    List<T>  results=commonService.createQuery(hql, list, page, rows);
		//count 为总条目数
		Long  count=commonService.getCount(hql, list);
		PageData grid_data=new PageData();
		grid_data.setValue(count.intValue(), results);
		return grid_data;
}
  private <T>  List search(Integer page, Integer rows,HttpServletRequest request,String modelName,String[] fields) throws Exception{
	  StringBuffer sb=new StringBuffer();
	  sb.append("select new map(");
	  for(int i=0;i<fields.length;i++)
	  {   String s=fields[i];
		  sb.append(" model.");
		  sb.append(s);
		  sb.append(" as ");
		  sb.append(s);
		  if(i!=fields.length-1)
			  sb.append(", ");
	  }
	  sb.append(")");
	  String selhql=sb.toString();
	  String  rigor=request.getParameter("rigor");
	  List result=HqlGenerateUtil.installHql(request.getParameterMap(), modelName, rigor);
	  String hql=(String)result.get(0);
	 // System.out.println(hql);
	  hql=sb.toString()+hql;
	  List list=(List)result.get(1);
	  List<T>  results=commonService.createQuery(hql, list, page, rows);
	  return results;
}
  
  private <T>  List search(Integer page, Integer rows,HttpServletRequest request,String modelName,String[] fields,String addtionHql) throws Exception{
	  StringBuffer sb=new StringBuffer();
	  sb.append("select new map(");
	  for(int i=0;i<fields.length;i++)
	  {   String s=fields[i];
		  sb.append(" model.");
		  sb.append(s);
		  sb.append(" as ");
		  sb.append(s);
		  if(i!=fields.length-1)
			  sb.append(", ");
	  }
	  sb.append(")");
	  String selhql=sb.toString();
	  selhql=selhql;
	  String  rigor=request.getParameter("rigor");
	  List result=HqlGenerateUtil.installHql(request.getParameterMap(), modelName, rigor);
	  String hql=(String)result.get(0);
	  //System.out.println(hql);
	  hql=sb.toString()+hql+addtionHql;
	  List list=(List)result.get(1);
	  List<T>  results=commonService.createQuery(hql, list, page, rows);
	  return results;
}
  
  private <T>  List search(Integer page, Integer rows,HttpServletRequest request,T searchObj,String[] fields) throws Exception{
	  StringBuffer sb=new StringBuffer();
	  sb.append("select new map(");
	  for(int i=0;i<fields.length;i++)
	  {   String s=fields[i];
		  sb.append(" model.");
		  sb.append(s);
		  sb.append(" as ");
		  sb.append(s);
		  if(i!=fields.length-1)
			  sb.append(", ");
	  }
	  sb.append(")");
	  String selhql=sb.toString();
	  String  rigor=request.getParameter("rigor");
	  List result=HqlGenerateUtil.installHql(request.getParameterMap(), searchObj, rigor);
	  String hql=(String)result.get(0);
	 // System.out.println(hql);
	  hql=sb.toString()+hql;
	  List list=(List)result.get(1);
	  List<T>  results=commonService.createQuery(hql, list, page, rows);
	  return results;
}
  private <T>  List search(Integer page, Integer rows,HttpServletRequest request,T searchObj,String[] fields,String addtionHql) throws Exception{
	  StringBuffer sb=new StringBuffer();
	  sb.append("select new map(");
	  for(int i=0;i<fields.length;i++)
	  {   String s=fields[i];
		  sb.append(" model.");
		  sb.append(s);
		  sb.append(" as ");
		  sb.append(s);
		  if(i!=fields.length-1)
			  sb.append(", ");
	  }
	  sb.append(")");
	  String selhql=sb.toString();
	  String  rigor=request.getParameter("rigor");
	  List result=HqlGenerateUtil.installHql(request.getParameterMap(), searchObj, rigor);
	  String hql=(String)result.get(0);
	  hql=hql+addtionHql;
	  //System.out.println(hql);
	  hql=sb.toString()+hql;
	  List list=(List)result.get(1);
	  List<T>  results=commonService.createQuery(hql, list, page, rows);
	  return results;
} 
  
  
 
	      
			
  
  
 }
